package com.lznAdmin.security.authentication.code;

import cn.hutool.core.util.StrUtil;
import com.lznAdmin.base.Const;
import com.lznAdmin.base.common.util.RedisUtil;
import com.lznAdmin.properties.SecurityProperties;
import com.lznAdmin.security.authentication.exception.ValidateCodeException;
import com.lznAdmin.security.config.CustomAuthenticationFailHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: lzn-manage-parent
 * @description: 验证码过滤校验器
 * @author: lzn
 * @create: 2021-07-27 10:05
 **/
@Component("imageCodeValidateFilter")
public class ImageCodeValidateFilter extends OncePerRequestFilter {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    SecurityProperties securityProperties;

    @Autowired
    CustomAuthenticationFailHandler customAuthenticationFailHandler;

    @Autowired
    RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 1. 如果是post方式 的登录请求，则校验输入的验证码是否正确
        if (securityProperties.getAuthentication().getLoginProcessingUrl().equals(request.getRequestURI())
                && request.getMethod().equalsIgnoreCase("post")) {
            try {
                // logger.info(JSON.toJSONString(request));
                // 校验验证码合法性
                validate(request);
            } catch (AuthenticationException exception) {
                // 交给失败处理器进行处理异常
                customAuthenticationFailHandler.onAuthenticationFailure(request, response, exception);
                // 务必记得要结束
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) throws ValidateCodeException {
        // 先获取token
        String token = request.getParameter("token");
        // 获取用户输入的验证码
        String inputCode = request.getParameter("code");
        logger.info(token + "=" + inputCode);
        // logger.info(request.getParameter());
        if (StrUtil.isBlank(token) || StrUtil.isBlank(inputCode)) {
            throw new ValidateCodeException("验证码不能为空");
        }
        // 通过token查询redis，判断是否正确
        if (!inputCode.equals(redisUtil.hget(Const.CAPTCHA_KEY, token))) {
            throw new ValidateCodeException("验证码输入错误");
        }
        redisUtil.hdel(Const.CAPTCHA_KEY, token);
    }
}
